%
% Author: Vasyl Mykhalchuk
%
% dir - name of dir in resources
function [ ] = temporalIntegration(dir, fileName, refId, fromId, toId )
cleanDir = dir;
outDir = strcat('..\..\target\', dir);
dir = strcat('..\..\res\', dir);

% Modify matlab path
addpath(genpath('../util'));
addpath(genpath('../io'));
addpath(genpath('../strain'));
addpath(genpath('../export'));
addpath(genpath('../obj-tools'));
addpath(genpath('..'));

% CLEAN THE TARGET
cleanTarget(cleanDir);

refFileName = getFileNameForId(fileName, refId);
referencePath = strcat(strcat(dir, '\'), refFileName);

[vertices, faces] = read_wobj(referencePath);
obj_ref.vertices = vertices;
obj_ref.faces = faces;
[nF, x] = size(faces);
[nV, x] = size(vertices);
obj_ref.nF = nF;
obj_ref.nV = nV;

% default initialization to zeroes
sfMinGlobal = zeros(obj_ref.nV, 1);
sfMaxGlobal = zeros(obj_ref.nV, 1);
sfMeanGlobal = zeros(obj_ref.nV, 1);

% compute adjacency lists
% List of faces adjacent to each vertex
LOG('Preprocessing');
adjList = createAdjacencyList(obj_ref.faces, obj_ref.nV, obj_ref.nF);
% List contains list of neighboring vertices for each vertex
adjVertList = createVertexAdjacencyList(obj_ref.faces, obj_ref.nV, obj_ref.nF);

% DEFORMATION FIELD
numberOfFrames = toId - fromId + 1;
deformationField = zeros(obj_ref.nV, numberOfFrames);

% STEP THROUGH FRAMES
stepCount = 0;
for targetId = fromId:toId
    targetFileName = getFileNameForId(fileName, targetId);
    targetFileName = strcat(strcat(dir, '\'), targetFileName);
    
    sf = nextSF(targetFileName, obj_ref, adjList, adjVertList);
    sfMeanGlobal = sfMeanGlobal + sf;
    stepCount = stepCount + 1;
    [sfMinGlobal, sfMaxGlobal] = calculateMinMax(sf, sfMinGlobal, sfMaxGlobal);
    deformationField(:, stepCount) = sf;
end%for

% CALCULATE ENTROPIES
hSF = zeros(obj_ref.nV, 1);
for i = 1:obj_ref.nV
    hSF(i) = entropy( deformationField(i, :), 4 );
end%for

% CALCULATE MEAN DURING THE ANIMATION
sfMeanGlobal = sfMeanGlobal / stepCount;
% SAVE RESULTS

%{
[nX, nY] = size(sfMaxGlobal);
hMax = entropy(reshape(sfMaxGlobal, 1, nX))
hMin = entropy(reshape(sfMinGlobal, 1, nX))
hMean = entropy(reshape(sfMeanGlobal, 1, nX))
%}
saveResultsOfTemporalIntegration(outDir, fileName, sfMinGlobal, sfMaxGlobal, sfMeanGlobal, hSF, obj_ref, adjVertList);

end%function temporalIntegration


